package com.leyou.order.utils;

import com.github.wxpay.sdk.WXPay;
import com.github.wxpay.sdk.WXPayConfigImpl;
import com.github.wxpay.sdk.WXPayConstants;
import com.github.wxpay.sdk.WXPayUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * @author 虎哥
 */
@Slf4j
@Component
public class PayHelper {

    private final WXPayConfigImpl payConfig;

    private final WXPay wxPay;

    public PayHelper(WXPayConfigImpl payConfig, WXPay wxPay) {
        this.payConfig = payConfig;
        this.wxPay = wxPay;
    }

    public String unifiedOrder(Long orderId, Long totalFee){
        // 有4个参数是由WxPay来填写，我们只需要传递剩下的6个
        // 6个请求参数：
        Map<String, String> data = new HashMap<String, String>();
        data.put("body", "乐优商城-购物款");
        data.put("out_trade_no", orderId.toString());
        data.put("total_fee", totalFee.toString());
        data.put("spbill_create_ip", payConfig.getSpbillCreateIp());
        data.put("trade_type", payConfig.getTradeType());  // 此处指定为扫码支付

        try {
            // 下单
            Map<String, String> resp = wxPay.unifiedOrder(data);

            // 对微信返回的数据做签名校验
            isSignatureValid(resp);

            // 获取支付交易链接
            String url = resp.get("code_url");
            if(StringUtils.isBlank(url)){
                log.error("获取url失败，原因：{}", resp.get("err_code_des"));
                // 说明url获取失败
                throw new RuntimeException("获取微信交易链接失败！" + resp.get("err_code_des"));
            }
            // 返回url
            return url;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public void isSignatureValid(Map<String, String> resp){
        boolean isValid = false;
        try {
            isValid = WXPayUtil.isSignatureValid(resp, payConfig.getKey(), WXPayConstants.SignType.HMACSHA256);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        if(!isValid){
            // 签名有误，数据是非法的
            throw new RuntimeException("签名有误，再捣乱我就报警了！");
        }
    }
}
